import {createRouter, createWebHashHistory, RouteRecordRaw} from 'vue-router'
import {getToken} from '../utils/storage'

/**
 * 路由配置
 * 包含用户认证页面和系统功能页面
 */
const routes: Array<RouteRecordRaw> = [
    {
        path: '/',
        name: 'Root',
        // 重定向到订单管理页面
        redirect: '/dashboard/order-list'
    },
    {
        path: '/login',
        name: 'Login',
        component: () => import('../views/user/Login.vue'),
        meta: {title: '登录'}
    },
    {
        path: '/register',
        name: 'Register',
        component: () => import('../views/user/Register.vue'),
        meta: {title: '注册'}
    },
    {
        path: '/dashboard',
        name: 'Dashboard',
        component: () => import('../views/Dashboard.vue'),
        meta: {
            requiresAuth: true,
            title: '财务共享中心'
        },
        redirect: '/dashboard/order-list',  // 默认重定向到订单列表
        children: [
            // 发票相关路由
            {
                path: 'invoice-list',
                name: 'InvoiceList',
                component: () => import('../views/invoice/InvoiceList.vue'),
                meta: {title: '发票列表'}
            },
            {
                path: 'invoice-add',
                name: 'InvoiceAdd',
                // 注意这里使用的是同一个组件，只是根据路由参数区分新增和编辑模式
                component: () => import('../views/invoice/InvoiceEdit.vue'),
                meta: {title: '新增发票'}
            },
            {
                path: 'invoice-edit/:id',
                name: 'InvoiceEdit',
                component: () => import('../views/invoice/InvoiceEdit.vue'),
                meta: {title: '编辑发票'}
            },
            {
                path: 'invoice-detail/:id',
                name: 'InvoiceDetail',
                component: () => import('../views/invoice/InvoiceDetail.vue'),
                meta: {title: '发票详情'}
            },
            {
                path: 'invoice-statistics',
                name: 'InvoiceStatistics',
                component: () => import('../views/invoice/InvoiceStatistics.vue'),
                meta: {title: '发票统计'}
            },

            // 订单管理相关路由
            {
                path: 'order-list',
                name: 'OrderList',
                component: () => import('../views/order/OrderList.vue'),
                meta: {title: '订单列表'}
            },
            {
                path: 'order-create',
                name: 'OrderCreate',
                component: () => import('../views/order/OrderEdit.vue'),
                meta: {title: '创建订单'}
            },
            {
                path: 'order-edit/:id',
                name: 'OrderEdit',
                component: () => import('../views/order/OrderEdit.vue'),
                meta: {title: '编辑订单'}
            },
            {
                path: 'order-detail/:id',
                name: 'OrderDetail',
                component: () => import('../views/order/OrderDetail.vue'),
                meta: {title: '订单详情'}
            },
            {
                path: 'order-statistics',
                name: 'OrderStatistics',
                component: () => import('../views/order/OrderStatistics.vue'),
                meta: {title: '订单统计'}
            },

            // 发货单管理相关路由
            {
                path: 'receipt-list',
                name: 'ReceiptList',
                component: () => import('../views/receipt/ReceiptList.vue'),
                meta: {title: '发货单列表'}
            },
            {
                path: 'receipt-create',
                name: 'ReceiptCreate',
                component: () => import('../views/receipt/ReceiptCreate.vue'),
                meta: {title: '创建收货单'}
            },
            {
                path: 'receipt-edit/:id',
                name: 'ReceiptEdit',
                component: () => import('../views/receipt/ReceiptEdit.vue'),
                meta: {title: '编辑发货单'}
            },
            {
                path: 'receipt-detail/:id',
                name: 'ReceiptDetail',
                component: () => import('../views/receipt/ReceiptDetail.vue'),
                meta: {title: '发货单详情'}
            },
            {
                path: 'receipt-statistics',
                name: 'ReceiptStatistics',
                component: () => import('../views/receipt/ReceiptStatistics.vue'),
                meta: {title: '收货单统计'}
            },

            // 三单匹配
            {
                path: 'match',
                name: 'MatchIndex',
                redirect: '/dashboard/match/integrated',  // 重定向到新的整合页面
                meta: {
                    title: '匹配管理',
                    icon: 'connection',
                    requiresAuth: true
                }
            },
            {
                path: 'match/integrated',
                name: 'MatchIntegrated',
                component: () => import('../views/match/MatchIntegrated.vue'),
                meta: {
                    title: '三单匹配',
                    icon: 'connection',
                    requiresAuth: true
                }
            },
            {
                path: 'match/available',
                name: 'MatchAvailable',
                redirect: '/dashboard/match/integrated',  // 重定向到新的整合页面
                meta: {
                    title: '可匹配订单',
                    icon: 'files',
                    requiresAuth: true
                }
            },
            {
                path: 'match/matched',
                name: 'MatchedList',
                component: () => import('../views/match/MatchedList.vue'),
                meta: {
                    title: '已匹配订单',
                    icon: 'checked',
                    requiresAuth: true
                }
            },
            {
                path: 'match/detail/:id',
                name: 'MatchDetail',
                component: () => import('../views/match/MatchDetail.vue'),
                meta: {
                    title: '匹配详情',
                    activeMenu: '/dashboard/match',
                    requiresAuth: true
                }
            },
            {
                path: 'match/three-way',
                name: 'MatchThreeWay',
                redirect: '/dashboard/match/integrated',  // 重定向到新的整合页面
                meta: {
                    title: '三单匹配',
                    icon: 'document',
                    requiresAuth: true
                }
            },

            // 匹配统计页面
            {
                path: 'match-statistics',
                name: 'MatchStatistics',
                component: () => import('../views/match/MatchStatistics.vue'),
                meta: {
                    title: '匹配统计',
                    requiresAuth: true
                }
            },

            // 在dashboard下的children路由数组中添加一个重定向路由
            {
                path: 'three-way-match',
                redirect: '/dashboard/match'
            },
        ]
    },
    {
        path: '/:pathMatch(.*)*',
        name: 'NotFound',
        component: () => import('../views/NotFound.vue'),
        meta: {title: '页面不存在'}
    }
]

const router = createRouter({
    history: createWebHashHistory(import.meta.env.BASE_URL),
    routes
})

// // 导航状态跟踪，用于检测循环重定向
// const navigationState = {
//     lastNavigationTime: 0,
//     lastPath: ''
// };

/**
 * 全局前置守卫
 * 处理页面标题和认证重定向
 */
router.beforeEach((to, from, next) => {
    // 设置页面标题
    if (to.meta.title) {
        document.title = to.meta.title as string;
    }

    // 如果是登录页面，已登录则跳转到首页
    if (to.path === '/login') {
        if (getToken()) {
            next({path: '/dashboard/order-list'});
        } else {
            next();
        }
        return;
    }

    // 检查是否需要认证
    const requiresAuth = to.matched.some(record => record.meta.requiresAuth);
    const token = getToken();

    if (requiresAuth && !token) {
        next({path: '/login'});
    } else {
        next();
    }
})

// 全局后置钩子
router.afterEach((to, from) => {
    // 设置页面标题
    if (to.meta.title) {
        document.title = to.meta.title as string
    } else {
        document.title = '智能财务共享中心'
    }

    // 滚动到页面顶部
    window.scrollTo(0, 0)
})

// 添加全局错误处理
router.onError((error) => {
    console.error('路由错误:', error)
    // 可以在这里添加额外的错误处理逻辑
    if (error.message.includes('Failed to fetch dynamically imported module')) {
        // 可以选择刷新页面或导航到错误页面
        // window.location.reload()
    }
})

export default router
